<?php

namespace App\Providers;

use App\Exceptions\BlackException;
use App\Helpers\Api\ApiResponse;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\ValidationException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class AppServiceProvider extends ServiceProvider
{
    use ApiResponse;
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment() !== 'production') {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
        //
        $this->app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) {
            $fractal = new \League\Fractal\Manager;
            $fractal->setSerializer(new \App\Serializers\DataArraySerializer);
            return new \Dingo\Api\Transformer\Adapter\Fractal($fractal);
        });

        app('Dingo\Api\Exception\Handler')->register(function (ValidationException $e) {
            $data = $e->validator->getMessageBag();
            $msg = collect($data)->first();
            if(is_array($msg)){
                $msg = $msg[0];
            }
            return $this->failed($msg, 422);
        });

        app('Dingo\Api\Exception\Handler')->register(function (TokenInvalidException $e) {
            return $this->failed('token无效重新授权', 401);
        });

        app('Dingo\Api\Exception\Handler')->register(function (TokenExpiredException $e) {
            return $this->failed('token过期，重新授权', 401);
        });

        app('Dingo\Api\Exception\Handler')->register(function (BlackException $e) {
            return $this->failed($e->getMessage(), $e->getCode());
        });

    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        if (env('LOG_DB_ON', true)) {
            \DB::listen(function ($query) {
                $tmp = str_replace('?', '"'.'%s'.'"', $query->sql);
                $qBindings = [];
                foreach ($query->bindings as $key => $value) {
                    if (is_numeric($key)) {
                        $qBindings[] = $value;
                    } else {
                        $tmp = str_replace(':'.$key, '"'.$value.'"', $tmp);
                    }
                }
                $tmp = vsprintf($tmp, $qBindings);
                $tmp = str_replace("\\", "", $tmp);
                \Log::info(' execution time: '.$query->time.'ms; '.$tmp);

            });
        }
    }
}
